#!/bin/bash

function getJsonValue(){
    grepKey=$1
    grepFile=$2

    cat $grepFile  |jq "${grepKey}" | sed 's/"//g'

}

function main(){
    memoryFile='/tmp/memory.json'

    lshw -C memory -json > $memoryFile
    memory_json_id=0
    for str in `cat $memoryFile |jq .[].id`;
    do
        echo $str |grep 'memory' >/dev/null
        if [ $? -eq 0 ];then
            break
        fi
        let memory_json_id++
    done
    memorySlots=`cat $memoryFile | jq '[.[] | select(.id | test("bank:"))] | length'`
    for ((i=0; i<$memorySlots; i++));
    do
        returnValue=`getJsonValue ".[$memory_json_id + $i + 1].size" $memoryFile`
        if [ "$returnValue" == "null" ];then
            continue
        fi
        echo -n "size=$(( returnValue / 1048576 )) MB;"
        ## brand
        returnValue=`getJsonValue ".[$memory_json_id + $i + 1].vendor" $memoryFile`
        echo -n "brand=${returnValue};"

        ## sn
        ram_sn=`getJsonValue ".[$memory_json_id + $i + 1].serial" $memoryFile`
        echo -n "sn=${ram_sn};"

        ## speed
        returnValue=`getJsonValue ".[$memory_json_id + $i + 1].clock" $memoryFile`
        echo -n "speed=$(( $returnValue / 1000000 )) MT/s;"

        ## model
        returnValue=`getJsonValue ".[$memory_json_id + $i + 1].product" $memoryFile`
        echo -n "model=${returnValue};"
        ## slot
        returnValue=`getJsonValue ".[$memory_json_id + $i + 1].slot" $memoryFile`
        echo -n "slot=${returnValue};"

        ## memory type ddr3|ddr4
        returnValue=`getJsonValue ".[$memory_json_id + $i + 1].description" $memoryFile`
        for k in {2..5};
        do
            echo $returnValue | grep "DDR${k}" > /dev/null
            if [ $? -eq 0 ];then
                echo -n "type=DDR${k};"
                break;
            fi
        done

        ## memory rank
        rank=`dmidecode -t memory |grep -A 5 ${ram_sn} |grep Rank |awk '{print $2}'`
        echo -n "rank=${rank};"

        echo "category=ram"
    done
}

main
